package cn.com.cpic.insurance.rulecheck.consumer.impl;

import org.apache.commons.lang.StringUtils;

import cn.com.cpic.insurance.rulecheck.consumer.BooleanResult;
import cn.com.cpic.insurance.rulecheck.consumer.BooleanRuleConsumer;
import cn.com.cpic.insurance.rulecheck.core.Context;
import cn.com.cpic.insurance.rulecheck.core.operator.Operator;
import cn.com.cpic.insurance.rulecheck.core.operator.OperatorUtils;

/**
 * 二元运算比较。
 * @author 林青
 */
public abstract class DyadicCompareConsumer implements BooleanRuleConsumer {

	public BooleanResult consume(Context context, String[] args) {
		String leftName = args[0];
		String rightName = args[1];
		String leftLabel = args[2];
		String rightLabel = args[3];
		boolean leftRequired = Boolean.parseBoolean(args[4]);
		boolean rightRequired = Boolean.parseBoolean(args[5]);
		int operator = Integer.parseInt(args[6]);
		BooleanResult result = new BooleanResult();
		if (context != null) {
			Object leftValue = context.getRtParam().get(leftName);
			Object rightValue = context.getRules().get(rightName);
			if (leftValue == null || StringUtils.isBlank(leftValue.toString())) {
				if (leftRequired) {
					result.addResult(false).addMessage("必须填写" + leftLabel);
				} else {
					return result.addResult(true);
				}
			}
			if (rightValue == null || StringUtils.isBlank(rightValue.toString())) {
				if (rightRequired) {
					result.addResult(false).addMessage("必须配置" + rightLabel);
				} else {
					return result.addResult(true);
				}
			}
			if (result.getMessages().size() != 0) {
				return result;
			}
			String leftVal = leftValue.toString().trim();
			String rightVal = rightValue.toString().trim();
			Operator op = OperatorUtils.getOperator(operator);
			try {
				if (op.calculate(leftVal, rightVal)) {
					return result.addResult(true);
				} else {
					result.addResult(false).addMessage(op.getFalseMessage(leftLabel, rightVal));
				}
			} catch (Exception e) {
				result.addResult(false).addMessage(leftLabel + "格式错误");
			}
		} else {
			throw new IllegalArgumentException("上下文对象未初始化。");
		}
		return result;
	}
}
